package com.qrback.service.impl;

import com.qrback.entity.User;
import com.qrback.utils.JwtUtils;
import com.qrback.repository.UserRepository;
import com.qrback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Value("${jwt.secret}")
    private String jwtSecret;
    
    @Value("${jwt.expiration}")
    private long jwtExpiration;
    
    @Override
    public Optional<User> getUserById(Integer id) {
        return userRepository.findById(id);
    }
    
    @Override
    public Optional<User> getUserByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
    
    @Override
    public boolean existsByPhone(String phone) {
        return userRepository.existsByPhone(phone);
    }
    
    @Override
    public User createUser(User user) {
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }
    
    @Override
    public User updateUser(User user) {
        User existingUser = userRepository.findById(user.getId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 更新非空字段
        if (user.getPhone() != null) {
            existingUser.setPhone(user.getPhone());
        }
        if (user.getPassword() != null) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        if (user.getRole() != null) {
            existingUser.setRole(user.getRole());
        }
        
        return userRepository.save(existingUser);
    }
    
    @Override
    public void deleteUser(Integer id) {
        userRepository.deleteById(id);
    }
    
    @Override
    public String login(String phone, String password) {
        User user = userRepository.findByPhone(phone)
                .orElseThrow(() -> new RuntimeException("手机号或密码错误"));
        
        if (!passwordEncoder.matches(password,user.getPassword())) {
            throw new RuntimeException("手机号或密码错误");
        }
        
        // 生成JWT令牌
        String token = jwtUtils.generateToken(user.getPhone(), user.getId(), user.getRole().name());
        System.out.println("用户登录成功 - 手机号: " + phone + ", 用户ID: " + user.getId() + ", Token: " + token);

        return token;
    }
    
    @Override
    public void sendVerificationCode(String phone) {
        // 检查用户是否存在
        User user = userRepository.findByPhone(phone)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 生成验证码
        String code = generateVerificationCode();
        
        // 这里简化实现，实际项目中需要调用短信服务发送验证码
        System.out.println("验证码: " + code + " 已发送到手机: " + phone);
        
        // 保存验证码到缓存（实际项目中需要使用Redis等缓存）
    }
    
    @Override
    public String loginWithVerificationCode(String phone, String code) {
        // 这里简化实现，实际项目中需要验证缓存中的验证码
        // 验证通过后生成JWT令牌
        return "generated_jwt_token_with_verification_code";
    }
    
    // 生成6位数字验证码
    private String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}